package com.tencreat.service.mall.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.tencreat.common.config.RabbitMqConfig;
import com.tencreat.common.config.WxConfig;
import com.tencreat.common.exception.CustomException;
import com.tencreat.domain.account.MallUser;
import com.tencreat.domain.mall.dto.WxApiUnionIdDTO;
import com.tencreat.domain.mall.vo.ResWxApiUnionIdVO;
import com.tencreat.service.account.IMallUserService;
import com.tencreat.service.mall.IMallGoodsCutService;
import com.tencreat.service.mall.IWxService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 描述信息WxServiceImpl
 *
 * @author zixin
 * @company 深圳腾创互联科技有限公司
 * @link https://tencreat.com
 * @since 2022/2/15 15:48
 */

@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class WxServiceImpl implements IWxService {

    @Autowired
    private IMallUserService mallUserService;

    @Autowired
    private RabbitMqConfig rabbitMqConfig;

    //@Autowired
    private IMallGoodsCutService goodsCutService;

    @Override
    public ResWxApiUnionIdVO getUnionId(WxApiUnionIdDTO dto) {
        WxConfig wxConfig = WxConfig.getWxConfig();
        String openidUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={}&secret={}&code={}&grant_type=authorization_code";
        String unionIdUrl = "https://api.weixin.qq.com/sns/userinfo?access_token={}&openid={}";
        String appId;
        String appSecret;
        String openid;
        String accessToken;
        String unionId;
        String avatar;
        String nickname;
        // 公众号
        if (dto.getClientType() == WxApiUnionIdDTO.ClientType.OFFICIAL.getValue()) {
            appId = wxConfig.getOfficialAppId();
            appSecret = wxConfig.getOfficialAppSecret();
        }
        // App
        else if (dto.getClientType() == WxApiUnionIdDTO.ClientType.APP.getValue()) {
            appId = wxConfig.getAppAppId();
            appSecret = wxConfig.getAppAppSecret();
        } else {
            throw new CustomException("类型错误");
        }
        openidUrl = StrUtil.format(openidUrl, appId, appSecret, dto.getCode());
        // 获取用户openID
        String res = HttpUtil.get(openidUrl);
        JSONObject resJson = JSONObject.parseObject(res);
        if (resJson.getInteger("errcode") == null && resJson.getInteger("expires_in") == 7200) {
            openid = resJson.getString("openid");
            accessToken = resJson.getString("access_token");
        } else {
            log.error("获取openid时失败" + res);
            throw new CustomException("获取openid时失败");
        }
        // 获取unionId
        unionIdUrl = StrUtil.format(unionIdUrl, accessToken, openid);
        res = HttpUtil.get(unionIdUrl);
        resJson = JSONObject.parseObject(res);
        log.info(res);
        if (resJson.getInteger("errcode") == null) {
            unionId = resJson.getString("unionid");
            nickname = resJson.getString("nickname");
            avatar = resJson.getString("headimgurl");
        } else {
            log.error("获取unionId时失败" + res);
            throw new CustomException("获取unionId时失败");
        }
        ResWxApiUnionIdVO result = new ResWxApiUnionIdVO();
        result.setUnionId(unionId);
        result.setAvatar(avatar);
        result.setNickname(nickname);
        return result;
    }

    @Override
    public void bindWx(WxApiUnionIdDTO dto) {
        ResWxApiUnionIdVO vo = getUnionId(dto);
        // 判断当前unionId是否被别的账号使用
        int count = mallUserService.lambdaQuery().eq(MallUser::getUnionId, vo.getUnionId()).count();
        if (count > 0) {
            throw new CustomException("此微信已被绑定");
        }
        // 绑定
        boolean isU = mallUserService.lambdaUpdate().eq(MallUser::getUuid, dto.getUserId()).set(MallUser::getUnionId, vo.getUnionId()).update();
        if (isU) {
            // 绑定成功处理砍价业务
            goodsCutService.cutAfterReward2(vo.getUnionId());
        }
    }
}
